from Config.myConstant import *
from Config.myConfig import *
from DataPrepare.tickFactors.factorBase import factorBase
from DataAccess.TickDataProcess import TickDataProcess
import pandas as pd
import numpy as np
########################################################################
class targetFactor(factorBase):
    """描述训练目标的函数"""
    #----------------------------------------------------------------------
    def __init__(self):
        #super(buySellVolumeRatio,self).__init__()
        super().__init__()
        self.factor='targetFactor'
        pass
    #----------------------------------------------------------------------
    def getFactorFromLocalFile(self,code,date):
        mydata=super().getFromLocalFile(code,date,'targetFactor')
        return mydata
        pass
    #----------------------------------------------------------------------
    def updateFactor(self,code,date,data=pd.DataFrame()):
        exists=super().checkLocalFile(code,date,self.factor)
        if exists==True:
            logger.info(f'No need to compute! {self.factor} of {code} in {date} exists!')
            pass
        if data.shape[0]==0:
             #data=TickDataProcess().getDataByDateFromLocalFile(code,date)
             data=TickDataProcess().getTickShotDataFromInfluxdbServer(code,date)
        result=self.computerFactor(code,date,data)
        super().updateFactor(code,date,self.factor,result)

    def f(group1):
            group1['realclosegainrate'] = group1['realclose'].shift(-5) / group1['realclose'] - 1
            return group1['realclosegainrate']

    #----------------------------------------------------------------------
    def computerFactor(self,mydata):

        result=pd.DataFrame()
        if mydata.shape[0]!=0:
            result=mydata[['adj_factor','close','date','code']].copy()
            result['realclose']=mydata['adj_factor']*mydata['close']
            data0 = result[['code', 'realclose', 'date']]

            def f(group):
                group['realclosegainrate'] = group['realclose'].shift(-5) / group['realclose'] - 1
                return group['realclosegainrate']
            data1 = pd.DataFrame(data0.groupby(data0['code']).apply(f))
            data1 = data1.reset_index()
            data1 = data1.set_index('level_1')
            data1['date']=data1.index.strftime('%Y%m%d')
            # result = result.reset_index()
            # result['level_1']=result['index']
            # result = pd.merge(result, data1, on=['code', 'level_1'])
            # result =result.set_index()
            # select = result['realclosegainrate'].isna() == True
            # result.loc[select, 'realclosegainrate'] = 0
            pass
        else:
            logger.error(f'There no data of  to computer factor!')
        return data1
########################################################################
